//
//  CZForwordController.swift
//  GZWeibo007
//
//  Created by 易辉华 on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD

// 统一管理cell的ID
enum CZStatusDetailIdentifier: String {
    case DetailStatusNormalCell = "DetailStatusNormalCell"
    case DetailStatusForwardCell = "DetailStatusForwardCell"
    case DetailCommentCell = "DetailCommentCell"
    case DetailLoadingCell = "DetailLoadingCell"
    case DetailNoDataCell = "DetailNoDataCell"
    
    // 判断返回对应的cellId
    static func cellId(obj: AnyObject) -> String {
        if obj is CZStatus {
            return (obj as! CZStatus).retweeted_status == nil ? DetailStatusNormalCell.rawValue : DetailStatusForwardCell.rawValue
        } else if obj is CZDetailCommentModel {
            return (obj as! CZDetailCommentModel).loading ? DetailLoadingCell.rawValue : DetailCommentCell.rawValue
        }
//        else if obj is CZDetailCommentModel {
//            return (obj as! CZDetailCommentModel).loading
//        }
        
        return DetailStatusNormalCell.rawValue
    }
}


class CZForwordController: UIViewController, UITableViewDelegate, UITableViewDataSource,CZStatusBottomViewDelegate, CZDetailHeaderViewDelegate {
    //MARK: - 属性
    //微博模型
    private var status: CZStatus
    //评论模型
    private var comments: [CZDetailCommentModel] = [CZDetailCommentModel]()
    
    
    init(status: CZStatus) {
        self.status = status
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "微博详情"
        prepareUI()
        prepareTabelViewUI()
    }
    //准备tabelView
    private func prepareTabelViewUI() {
        tableView.backgroundColor = UIColor(white: 0.9, alpha: 1)
        tableView.estimatedRowHeight = 300
        
        // 注册cell
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailStatusNormalCell.rawValue)
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailStatusForwardCell.rawValue)
        
        tableView.registerClass(CZCommentCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailCommentCell.rawValue)
        
        tableView.registerClass(CZDetailLoadingCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailLoadingCell.rawValue)
        
        tableView.registerClass(CZDetailNoDataCell.self, forCellReuseIdentifier: CZStatusDetailIdentifier.DetailNoDataCell.rawValue)
        
        tableView.dataSource = self
        tableView.delegate = self
        // 添加上拉加载更多控件
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            // 加载更多数据
            print("加载更多评论")
            self.loadMoreComment()
        }
        tableView.tableFooterView = UIView()
    }
    // MARK: - tableView头部代理
    func detailHeaderViewClick(headerView: UIView) {
        // 加载 `最新评论`
        print("加载评论")
        loadNewComment()
    }
    
    // MARK: - 加载最新评论
    /// 加载最新评论
    private func loadNewComment() {
        let since_id = comments.first?.id ?? 0
        
        // 添加 正在加载数据的cell
        let loadCommentModel = CZDetailCommentModel(loading: true)
        comments.insert(loadCommentModel, atIndex: 0)
        
        // 重新刷新数据
        tableView.reloadData()
        
        // 滚动到第1组第0个cell
        tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
        
        CZDetailCommentModel.loadComment(status.id, since_id: since_id, max_id: 0) { (comments, total_number, previous_cursor, next_cursor, error) -> () in
            
            // 移除正在加载数据的cell
            self.comments.removeFirst()
            
            if error != nil {
                print("加载最新评论失败: \(error)")
                SVProgressHUD.showErrorWithStatus("加载最新评论失败")
                // 重新刷新数据
                self.tableView.reloadData()
                return
            }
            
            print("加载最新评论成功:\(comments?.count), next_cursor: \(next_cursor)")
            self.status.comments_count = total_number!
            
            //            SVProgressHUD.showInfoWithStatus("加载 \(comments?.count ?? 0) 条最新评论")
            
            // 判断是否加载到数据
            if comments != nil && comments?.count > 0 {
                
                // 将新获取到的数据拼接在现有数据的前面
                self.comments = comments! + self.comments
            }
            
            // 重新刷新数据
            self.tableView.reloadData()
        }
    }
    // MARK: - 加载更多评论
    /// 加载更多评论
    private func loadMoreComment() {
        CZDetailCommentModel.loadComment(status.id, since_id: 0, max_id: comments.last?.id ?? 0) { (comments, total_number, previous_cursor, next_cursor, error) -> () in
            // 停止上拉加载更多数据动画
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                SVProgressHUD.showErrorWithStatus("加载更多评论失败")
                print("加载更多评论失败: \(error)")
                return
            }
            
            print("加载更多评论成功:\(comments?.count), next_cursor: \(next_cursor)")
            self.status.comments_count = total_number!
            
            //            SVProgressHUD.showInfoWithStatus("加载 \(comments?.count ?? 0) 条更多评论")
            
            self.tableView.showsInfiniteScrolling = next_cursor != 0
            
            // 判断是否加载到数据
            if comments != nil && comments?.count > 0 {
                // 将新获取到的数据拼接在现有数据的后面
                self.comments = self.comments + comments!
                
                // 重新刷新数据
                self.tableView.reloadData()
            }
            
        }
    }
    
    
    //准备UI
    private func prepareUI() {
        //添加控件
        view.addSubview(tableView)
        view.addSubview(bottomView)
        //取消Auto
        tableView.translatesAutoresizingMaskIntoConstraints = false
        bottomView.translatesAutoresizingMaskIntoConstraints = false
        
        // tableView水平
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : tableView]))
   
        // bottomView水平
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bv" : bottomView]))
        
        // 垂直方向
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[tb]-0-[bv(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : tableView, "bv": bottomView]))
        
    }
    
    //MARK: - tableView的代理方法
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    //每组显示几个Cell
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        } else {
            if comments.count == 0 {
                return comments.count
            } else {
                return comments.count
            }
        }
    }
    //cell的高度
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            
            let cellId = CZStatusDetailIdentifier.cellId(status)
            
            let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
            
            let rowHeight = cell.rowHeight(status)
            
            return rowHeight
        } else {
            return UITableViewAutomaticDimension
        }
    }
    //每个Cell的内容
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
        let cellId = CZStatusDetailIdentifier.cellId(status)
            
        let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZStatusCell
            
        cell.status = status
        
        return cell
        } else {
            if comments.count == 0 {
                let cell = tableView.dequeueReusableCellWithIdentifier(CZStatusDetailIdentifier.DetailNoDataCell.rawValue) as! CZDetailNoDataCell
                cell.message = "还没有人评论"
                return cell
            } else {
                let commentModel = comments[indexPath.row]
                
                let cellId = CZStatusDetailIdentifier.cellId(commentModel)
                
                let cell = tableView.dequeueReusableCellWithIdentifier(cellId) as! CZCommentCell
                
                cell.model = commentModel
                
                return cell
            }
        }
    }
   
    /// tableView每组头部视图
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 {   // 第一组显示头部控件
            detailHeaderView.status = self.status
            return detailHeaderView
        } else {    // 其他组没有头部控件
            return nil
        }
    }
    
    /// tableView每组头部高度
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 44
        } else {
            return 0
        }
    }

    
    //代理方法的实现
    func ZFBtnClick() {
        let zf = CZZFViewController(status: status)
        zf.hidesBottomBarWhenPushed = true
//        navigationController?.pushViewController(zf, animated: true)
        presentViewController(UINavigationController(rootViewController: zf), animated: true, completion: nil)
    }
    func PLBtnClick() {
        let pl = CZPLViewController(status: status)
        pl.hidesBottomBarWhenPushed = true
//        navigationController?.pushViewController(pl, animated: true)
        presentViewController(UINavigationController(rootViewController: pl), animated: true, completion: nil)
    }

    //MARK: - 懒加载
    /// tableView
    private lazy var tableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Plain)
    
    ///headView
    private lazy var detailHeaderView: CZDetailHeaderView = {
        
        let view = CZDetailHeaderView()
        view.delegate = self
        
        view.status = self.status

        return view
    }()
    /// 底部View
    private lazy var bottomView: CZStatusBottomView = {
        let view = CZStatusBottomView()
    view.delegate = self
        return view
    }()

    
}
